package com.homer.iot.esptouch.tcp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;

import com.homer.iot.esptouch.model.Slaver;
import com.homer.iot.esptouch.model.SlaverAlloc;

public class TCPSocketClient {
	static Socket client;
	private String serverIp;
	private int serverPort;
	InputStream input;
	OutputStream output;

	public TCPSocketClient(String serverIp, int serverPort) {
		super();
		this.serverIp = serverIp;
		this.serverPort = serverPort;
	}

	/**
	 * 建立连接.
	 * 
	 * @return
	 */
	public boolean connection() {
		try {
			client = new Socket();
			SocketAddress sockAdd = new InetSocketAddress(serverIp, serverPort);
			client.connect(sockAdd, 2000);
			input = client.getInputStream();
			output = client.getOutputStream();
			return true;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 查询协议： 5A 00 00 00 00 00 00 00 00 A5
	 * 
	 * @param content
	 */
	public void sendData(byte[] buffer) {
		try {
			output.write(buffer);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 5A 00 00 00 01 00 00 01 00 A5 其中00 00 00 01是ID
	 * 
	 * @return
	 */
	public byte[] getDeviceId() {
		//byte[] b = new byte[4];
		byte[] b = new byte[4];
		// while (true)
		{
			byte[] buf = new byte[1024];
			System.out.println("InputStream===" + input);
			if (input != null) {
				try {
					int len = input.read(buf);
					if (len >= 10 && buf[0] == 0x5A) {
						b[0] = buf[1];
						b[1] = buf[2];
						b[2] = buf[3];
						b[3] = buf[4];
						// break;
					} else {
						b = null;
						// break;
					}
				} catch (IOException e) {
					return null;
				}
			}
		}

		return b;

	}

	public Byte getSingleValue() {
		byte[] b = new byte[1];
		// while (true)
		{
			byte[] buf = new byte[15];
			System.out.println("InputStream===" + input);
			if (input != null) {
				try {
					int len = input.read(buf);
					if (len >= 10 && buf[0] == 0x5A) {
						b[0] = buf[9];

						// break;
					} else {
						b = null;
						// break;
					}
				} catch (IOException e) {
					return null;
				}

			}
		}

		return b[0];

	}
	public byte[] getDoubleValue() {
		byte[] b = new byte[2];
		// while (true)
		{
			byte[] buf = new byte[15];
			System.out.println("InputStream===" + input);
			if (input != null) {
				try {
					int len = input.read(buf);
					if (len >= 10 && buf[0] == 0x5A) {
						b[0] = buf[9];
						b[1] = buf[10];
						// break;
					} else {
						b = null;
						// break;
					}
				} catch (IOException e) {
					return null;
				}

			}
		}

		return b;

	}

	/**
	 * 答复报文范例“5A 00 00 00 03 00 00 0F 06 46 76 01 E5 72 03 A5”，“0F
	 * 06”表示KEY为0x0f，06表示后面有6字节数据，“46 76 01”表示地址为0x4676的开关，“E5 72
	 * 03”表示地址为0xe572的红外。
	 * 
	 * @return
	 */
	public List<Slaver> getSlaverList() {
		List<Slaver> slaverList = new ArrayList<Slaver>();
		// while (true)
		{
			byte[] buf = new byte[1024];
			System.out.println("InputStream===" + input);
			if (input != null) {
				try {
					int len = input.read(buf);
					if (len >= 10 && buf[0] == 0x5A) {
						byte[] bjq = new byte[2];
						bjq[0] = buf[7];
						bjq[1] = buf[8];

						if (bjq[0] == 0x0f) {
							int leng = bjq[1];
							// int count = leng/3;
							// for(int j = )

							if (leng % 3 == 0) {
								// byte[] bjq2 = new byte[leng];
								for (int i = 9; i < 9 + leng; i += 3) {

									// bjq2[i] = buf[i];
									byte[] id = new byte[4];
									id[0] = 0x00;
									id[1] = 0x00;
									id[2] = buf[i];
									id[3] = buf[i + 1];
									
									
									int type = buf[i + 2];
									
									//short value;
									//value = (short)((((short)id[0]) & 0xFF)<< 8 | ((short)(id[0 + 1] & 0xFF)));
											//| ((src[0 + 2] & 0xFF) << 16) | ((src[0 + 3] & 0xFF) << 24)
									int value;
									value = bytesToInt2(id, 0);
									if(value < 0)
									{
										byte[] id2 = new byte[4];
										id2[0] = 0x00;
										id2[1] = 0x00;
										id2[2] = buf[i+1];
										id2[3] = buf[i];
										value = bytesToInt2(id2, 0);
									}
									
									Slaver slaver = SlaverAlloc.alloc(
											value +"", type);
									if (null != slaver) {
										slaverList.add(slaver);
									}
								}
							}
						}
					} else {
						return null;
					}
				} catch (IOException e) {
					return null;
				}

			}
		}

		return slaverList;
	}

	/**
	 * 截取byte数据
	 * 
	 * @param b
	 *            是byte数组
	 * @param j
	 *            是大小
	 * @return
	 */
	public static byte[] cutOutByte(byte[] b, int j) {
		if (b.length == 0 || j == 0) {
			return null;
		}
		byte[] bjq = new byte[j];
		for (int i = 1; i < j; i++) {
			bjq[i] = b[i];
		}
		return bjq;
	}
	
	/** 
     * byte数组中取int数值，本方法适用于(低位在前，高位在后)的顺序，和和intToBytes（）配套使用
     *  
     * @param src 
     *            byte数组 
     * @param offset 
     *            从数组的第offset位开始 
     * @return int数值 
     */  
	public static int bytesToInt(byte[] src, int offset) {
		int value;	
		value = (int) ((src[offset] & 0xFF) 
				| ((src[offset+1] & 0xFF)<<8) 
				| ((src[offset+2] & 0xFF)<<16) 
				| ((src[offset+3] & 0xFF)<<24));
		return value;
	}
	
	 /** 
     * byte数组中取int数值，本方法适用于(低位在后，高位在前)的顺序。和intToBytes2（）配套使用
     */
	public static int bytesToInt2(byte[] src, int offset) {
		int value;	
		value = (int) ( ((src[offset] & 0xFF)<<24)
				|((src[offset+1] & 0xFF)<<16)
				|((src[offset+2] & 0xFF)<<8)
				|(src[offset+3] & 0xFF));
		return value;
	}

	public void close() {
		if (null != client) {
			try {
				client.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			client = null;
		}

	}
}
